package com.atguigu.day05;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;

public class Example5_2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.readTextFile("D:\\WebSite\\flink\\flink\\java_flink\\src\\main\\resources\\UserBehavior.csv")
                .map(x -> {
                    String[] arr = x.split(",");
                    return new UserBehavior(
                            arr[0],
                            arr[1],
                            arr[2],
                            arr[3],
                            Long.parseLong(arr[4])
                    );
                })
                .returns(Types.POJO(UserBehavior.class))
                .filter(x -> x.behavior.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forMonotonousTimestamps()
                                .withTimestampAssigner((SerializableTimestampAssigner<UserBehavior>) (element, recordTimestamp) -> element.timestamp)
                )
                .keyBy(x -> x.itemId)
                .process(new FakeWindow(1L))
                .keyBy(x->x.endTime)
                .process(new KeyedProcessFunction<Long, ItemViewCount, String>() {
                    private ListState<Tuple2<String, Long>> listState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        listState = getRuntimeContext().getListState(new ListStateDescriptor<Tuple2<String, Long>>(
                                "list_Stage", Types.TUPLE(Types.STRING, Types.LONG)
                        ));
                    }

                    @Override
                    public void processElement(ItemViewCount value, Context ctx, Collector<String> out) throws Exception {
                        ctx.timerService().registerEventTimeTimer(value.endTime + 1L);
                        listState.add(Tuple2.of(value.itemId, value.count));
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        Iterator<Tuple2<String, Long>> iterator = listState.get().iterator();
                        ArrayList<Tuple2<String, Long>> list = new ArrayList<>();
                        while (iterator.hasNext()){
                            list.add(iterator.next());
                        }
                        list.sort((o1, o2) -> -(int) (o1.f1 - o2.f1));
                        StringBuilder sb = new StringBuilder();
                        sb
                                .append("****************************************\n");
                        for (int i = 0; i < 3; i++) {
                            sb.append("窗口结束时间：").append(new Timestamp(timestamp - 1)).append("第").append(i+1).append("名   商品ID：").append(list.get(i).f0).append("  浏览总量： ").append(list.get(i).f1).append("\n");
                        }
                        sb
                                .append("****************************************\n");
                        out.collect(sb.toString());
                    }
                })
                .print();


        env.execute();
    }

    public static class FakeWindow extends KeyedProcessFunction<String, UserBehavior, ItemViewCount> {
        private MapState<Long, Long> mapState;
        private Long windowSize;

        public FakeWindow(Long windowSize) {
            this.windowSize = windowSize * 60 * 60 * 1000L;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            mapState = getRuntimeContext().getMapState(new MapStateDescriptor<Long, Long>("longAndLong", Types.LONG, Types.LONG));
        }

        @Override
        public void processElement(UserBehavior value, Context ctx, Collector<ItemViewCount> out) throws Exception {
            long windowStart = value.timestamp - value.timestamp % windowSize;
            long windowStop = windowStart + windowSize;
            if (mapState.contains(windowStart)) {
                mapState.put(windowStart, mapState.get(windowStart) + 1L);
            } else {
                mapState.put(windowStart, 1L);
                ctx.timerService().registerEventTimeTimer(windowStop - 1L);
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<ItemViewCount> out) throws Exception {
            long windowStop = timestamp + 1L;
            long windowStart = windowStop - windowSize;
            Long count = mapState.get(windowStart);
            out.collect(new ItemViewCount(
                    ctx.getCurrentKey(),
                    windowStart,
                    windowStop,
                    count
            ));
            mapState.remove(windowStart);
        }
    }

    public static class ItemViewCount {
        public String itemId;
        public Long startTime;
        public Long endTime;
        public Long count;

        public ItemViewCount() {
        }

        @Override
        public String toString() {
            return "ItemViewCount{" +
                    "itemId='" + itemId + '\'' +
                    ", startTime=" + new Timestamp(startTime) +
                    ", endTime=" + new Timestamp(endTime) +
                    ", count=" + count +
                    '}';
        }

        public ItemViewCount(String itemId, Long startTime, Long endTime, Long count) {
            this.itemId = itemId;
            this.startTime = startTime;
            this.endTime = endTime;
            this.count = count;
        }
    }


    public static class UserBehavior {
        public String userId;
        public String itemId;
        public String categoryId;
        public String behavior;
        public Long timestamp;

        @Override
        public String toString() {
            return "UserBehavior{" +
                    "userId='" + userId + '\'' +
                    ", itemId='" + itemId + '\'' +
                    ", categoryId='" + categoryId + '\'' +
                    ", behavior='" + behavior + '\'' +
                    ", timestamp=" + new Timestamp(timestamp) +
                    '}';
        }

        public UserBehavior() {
        }

        public UserBehavior(String userId, String itemId, String categoryId, String behavior, Long timestamp) {
            this.userId = userId;
            this.itemId = itemId;
            this.categoryId = categoryId;
            this.behavior = behavior;
            this.timestamp = timestamp * 1000L;
        }
    }
}
